angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
  // Form data for the login modal
  $scope.loginData = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    console.log('Doing login', $scope.loginData);

    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };
})

.controller('PlaylistsCtrl', function($scope) {
  $scope.playlists = [
    { title: 'Reggae', id: 1 },
    { title: 'Chill', id: 2 },
    { title: 'Dubstep', id: 3 },
    { title: 'Indie', id: 4 },
    { title: 'Rap', id: 5 },
    { title: 'Cowbell', id: 6 }
  ];
})

.controller('IntroductionCtrl', function($rootScope, $scope, $stateParams, MyLocalStorage, Chats, $window, DBAPI) {
	if($rootScope.isSessionActive())
	{
		console.log("session is active");
		$window.location.href = ('#/app/browse');
	}
	else
	{
		console.log("Session is not active");
	}
	$scope.chat = Chats.get($stateParams.chatId);
})

.controller('SignInCtrl', function ($rootScope, $scope, DBAPI, $window) {
    $scope.user = {
        email: "",
        password: ""
    };
 
    $scope.validateUser = function () {
        var email = this.user.email;
        var password = this.user.password;
        if(!email || !password) {
        	$rootScope.notify("Please enter valid credentials");
        	return false;
        }
        $rootScope.show('Please wait.. Authenticating');
        DBAPI.signin({
            email: email,
            password: password
        }).success(function (data) {
        		console.log(data);
            $rootScope.setToken(email); // create a session kind of thing on the client side
            $rootScope.hide();
            //save user info into local storage before relocation
            console.log("write email " + email);
            $rootScope.setMyEmail(email);	
            console.log("write ee score" + data.eeScore);
    			$rootScope.setMyEEScore(data.eeScore);
    			$rootScope.setMyName(data.name);
    			$rootScope.setCountry(data.country);
    			$rootScope.setMyNOC(data.noc);
    			
    			console.log("read back ee score : " + $rootScope.getMyEEScore());
        	//
            $window.location.href = ('#/app/browse');
        }).error(function (error) {
            $rootScope.hide();
            if(!error)
            {
            	$rootScope.notify("Cannot connect to server");
            }
            else
            {
            	$rootScope.notify("invalid email or password");
            }
            
        });
    }
 
})

.controller('SignupCtrl', function($rootScope, $scope, DBAPI, $window, $stateParams) {
	console.log("log out $stateParams.country");
	console.log($stateParams.country);
	$scope.myCountry = $stateParams.country;
	
	console.log($scope.myCountry);
	
	$scope.gotoList = function(){
		//store the form before leaving
		//it looks like a stupid code, will find a way to resolve such case
		$rootScope.RegUser.email = this.user.email;
    		$rootScope.RegUser.password = this.user.password;
    		$rootScope.RegUser.EEScore = Number(this.user.EEScore);
    		$rootScope.RegUser.name = this.user.name;
    		$rootScope.RegUser.NOC = this.user.NOC;
		$window.location.href = ('#/countryList');
	}
    
    $scope.user = {
        email: "",
        password: "",
        name: "",
        EEScore :"",
        NOC :""
    };
    
    //restore the form back from other page
    $scope.user.email = $rootScope.RegUser.email;
    $scope.user.password = $rootScope.RegUser.password;
    $scope.user.EEScore = $rootScope.RegUser.EEScore;
    $scope.user.name = $rootScope.RegUser.name;
    $scope.user.NOC = $rootScope.RegUser.NOC;
    
    $scope.testFunc = function(){
    	$rootScope.show('hello test');
    }
 
    $scope.createUser = function () {
    	var email = this.user.email;
        var password = this.user.password;
        var uName = this.user.name;
        var ueeScore = this.user.EEScore;
        var uCountry = this.myCountry;
        var uNOC = this.user.NOC;
        
        //validate email
        if(!email) {
        	$rootScope.notify("email should not be empty");
        	return false;
        }
        //validate email format
        var emailPat= /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if(!email.match(emailPat))
        {
        	$rootScope.notify("Please enter valid email");
        	return false;
        }
        //
        
        //validate pwd
        if(!password) {
        	$rootScope.notify("Password should not be empty");
        	return false;
        }
        //
        
        //validate name
        if(!uName) {
        	$rootScope.notify("Name should not be empty");
        	return false;
        }
        //
        
        //validate EE Score
        if(!ueeScore) {
        	$rootScope.notify("EE Score should not be empty");
        	return false;
        }
        //validate ee score format
        var eeScorePat= /^([0-9])+$/;
        
        if((Number(ueeScore) < 0) || Number(ueeScore) > 1200)
        {
        	$rootScope.notify("EE Score should be from 0 to 1200");
        	return false;
        }
        //
        
        //validate NOC
        if(!uNOC) {
        	$rootScope.notify("NOC should not be empty");
        	return false;
        }
        //validate ee score format
        var nocPat= /^([0-9])+$/;
        if(!uNOC.match(nocPat))
        {
        	$rootScope.notify("Please enter valid NOC");
        	return false;
        }
        
        //validate country
        if(!uCountry) {
        	$rootScope.notify("Country should not be empty");
        	return false;
        }
        //
        
        $rootScope.show('Please wait.. Registering');
        DBAPI.signup({
            email: email,
            password: password,
            name: uName,
            eeScore: ueeScore,
            country: uCountry,
            noc : uNOC,
            invited : 1
        }).success(function (data) {
            $rootScope.setToken(email); // create a session kind of thing on the client side
            $rootScope.hide();
            
            //save user info into local storage before relocation
            $rootScope.setMyEmail(email);	
    		$rootScope.setMyEEScore(ueeScore);
    		$rootScope.setMyName(uName);
    		$rootScope.setCountry(uCountry);
    		$rootScope.setMyNOC(uNOC);
    		
    		console.log("read back my ee score: " + $rootScope.getMyEEScore());
            //
            console.log("Register success and ready to relocate");
            $window.location.href = ('#/app/playlists');
        }).error(function (error) {
            $rootScope.hide();
            console.log("Register error");
            if(!error)
            {
            	$rootScope.notify("Cannot connect to server");
            }
            else
            {
	        	if(error.error && error.error.code == 11000)
	        	{
	        		$rootScope.notify("A user with this email already exists");
	        	}
	        	else
	        	{
	        		$rootScope.notify("Oops something went wrong, Please try again!");
	        	}
            }
        });
    }
})

.controller('PlaylistCtrl', function($scope, $stateParams) {
});
